import paho.mqtt.client as mqtt
import json
import random
import time


class MQTTClient:
    def __init__(self, machine_name, client_id, broker_address='110.40.179.221', broker_port=1883,
                 username="ism", password="123456"):
        """
        :param machine_name: 设备名称，建议与client_id一样
        :param client_id: 用于连接mqtt服务器的标识，建议与设备名称一致
        :param broker_address: 服务器ip地址
        :param broker_port: 服务器端口
        """
        self.client = mqtt.Client(client_id)
        self.client.username_pw_set(username, password)
        self.machine_name = machine_name
        self.broker_address = broker_address
        self.broker_port = broker_port
        self.subscribe_topic = f"PrintMachine/{self.machine_name}/fiter"
        # 设置回调函数
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect

    def on_connect(self, client, userdata, flags, rc):
        print(f"成功连接MQTT服务器，连接信息:{rc}")
        # 订阅主题
        client.subscribe(self.subscribe_topic)

    def on_message(self, client, userdata, msg):
        print(f"收到主题是{msg.topic}的MQTT数据: {msg.payload.decode()}")

    def on_disconnect(self, client, userdata, rc):
        print(f"断开连接MQTT服务器，连接信息:{rc}")

    def connect(self):
        # 连接到MQTT服务器
        self.client.connect(self.broker_address, self.broker_port, 60)
        # 开始循环，保持连接
        self.client.loop_start()

    def disconnect(self):
        # 断开连接
        self.client.loop_stop()

    def publish(self, topic, message, json_flag=False):
        # 发布消息
        if not json_flag:
            self.client.publish(topic, message)
        else:
            _message = json.dumps(message)
            self.client.publish(topic, _message)


if __name__ == "__main__":
    # 创建MQTT客户端实例
    # mqtt_client = MQTTClient("Print6", "Print6")
    mqtt_client = MQTTClient("Print3", "Print3")

    # 连接到MQTT服务器
    mqtt_client.connect()

    for i in range(25):
        payload_dict = {"properties": {"PrintStatus": random.randint(0, 1),
                                       "TotalNum": random.randint(1, 1000)}}
        data = json.dumps(payload_dict)
        # 发布消息
        mqtt_client.publish(f"/sys/{mqtt_client.machine_name}/post", data)
        print(f"发布消息:{payload_dict}成功")
        time.sleep(5)

    # 等待一段时间，以便接收订阅的消息
    input("Press Enter to disconnect and exit...\n")

    # 断开连接
    mqtt_client.disconnect()
